package com.ericsson.enap.modules.kpi.task.ims;

import com.ericsson.common.quartz.task.ManualTask;
import com.ericsson.common.util.*;
import com.ericsson.enap.modules.kpi.entity.EnipFormula;
import com.ericsson.enap.modules.kpi.entity.ImsFiveKpi;
import com.ericsson.enap.modules.kpi.service.IEnipFormulaService;
import com.ericsson.enap.modules.kpi.service.ImsFiveKpiService;
import com.ericsson.enap.modules.kpi.thread.ImsFiveKpiDataProcessThread;
import com.ericsson.enap.modules.sys.entity.EpcDict;
import com.ericsson.enap.modules.sys.service.EpcDictService;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * ims指标处理
 */
@Component
public class ImsFiveKpiTask implements ManualTask {
    private Logger log = LoggerUtils.Logger(LogFileName.ImsFiveKpiJob);

    @Autowired
    private ImsFiveKpiService imsFiveKpiService;
    @Autowired
    private IEnipFormulaService enipFormulaService;
    @Autowired
    private EpcDictService epcDictService;
    @Autowired
    private MongoTemplate mongoTemplate;
    private static final String nettype="enip_base_netelement_type";

    @Value("${collectorIp}")
    private String collectorIp;

    @Override
    public void execute() {
       Date now = new Date();
        //删除过期数据
       deleteMongodbData(now);
       //查询IMS网元及下载路径 ims nettype //101:PSBCC  102:TAS   103:CSCF
       List<ImsFiveKpi> imsFiveKpis= imsFiveKpiService.findImsFiveKpiList(collectorIp);
       //6:对应ruoyi中 IMS五分钟采集器的数值
        EnipFormula enipFormulaQuery=new EnipFormula();
        enipFormulaQuery.setBizType(6);
       List<EnipFormula> enipFormulas= enipFormulaService.selectEnipFormulaList(enipFormulaQuery);
       //解析公式对应的Expression
        Map<String,List<EnipFormula>> enipFormulaMap=analysisFormulaExpression(enipFormulas);
        Map<String,String> netTypeNameMap= getNetMap();
        String storePath=downloadBasePath();
       for(ImsFiveKpi imsFiveKpi: imsFiveKpis) {
           List<EnipFormula> formulaList = enipFormulaMap.get(imsFiveKpi.getType().toString());

           ImsFiveKpiDataProcessThread imsFiveKpiDataProcessThread=new ImsFiveKpiDataProcessThread(imsFiveKpi, netTypeNameMap.get(imsFiveKpi.getType().toString()), formulaList, now, log,storePath);
           new Thread(imsFiveKpiDataProcessThread).start();
       }
    }

    private Map<String, String> getNetMap() {
        Map<String,String> netMap=new HashMap<>();
        netMap.put("101","PSBCCFIVE");
        netMap.put("102","TASFIVE");
        netMap.put("103","CSCFFIVE");
        return netMap;
    }

    /**
     * 删除过期数据
     * @param now
     */
    private void deleteMongodbData(Date now){
        EpcDict epcDict=new EpcDict();
        epcDict.setKeyName("IMSFIVEKPIMONGODBTIME");
        epcDict= epcDictService.selectEpcDict(epcDict);
        if(null!=epcDict&&!"".equals(epcDict.getKeyValue())) {
            String deleteTime = DateUtils.getStatisTime(Integer.parseInt(epcDict.getKeyValue())*1440+30,now,"yyyy-MM-dd HH:mm:00");
            log.info("deleteTime-------------------------------:"+deleteTime);
            Query query = Query.query(Criteria.where("dateTime").lte(deleteTime));
            mongoTemplate.remove(query,"imskpi_6_cscf");
            mongoTemplate.remove(query,"imskpi_6_tas");
            mongoTemplate.remove(query,"imskpi_6_psbcc");
            mongoTemplate.remove(query,"ims_cscf_multi_register");
            mongoTemplate.remove(query,"ims_cscf_multi_session");
        }
    }

    /**
     * 获取下载文件存储的基础目录
     * @return
     */
    private String downloadBasePath(){
        EpcDict epcDict=new EpcDict();
        epcDict.setKeyName("IMSFIVEKPISTOREPATH");
        epcDict= epcDictService.selectEpcDict(epcDict);
        if(null!=epcDict&&!"".equals(epcDict.getKeyValue())) {
            return epcDict.getKeyValue();
        }else{
            return "/opt";
        }
    }

    /**
     * 处理公式的Expression
     * @param formulaList
     * @return
     */
    private Map<String,List<EnipFormula>> analysisFormulaExpression(List<EnipFormula> formulaList){
        for (Iterator iter = formulaList.iterator(); iter.hasNext(); ) {
            EnipFormula f = (EnipFormula) iter.next();
            String formulaText = FormulaConvertImsFive.getResult(f.getFormula());
            try {
                //Expression compiledExp = AviatorEvaluator.compile(formulaText.replaceAll("contains ","contains").replaceAll("not_contains ","not_contains").replaceAll("not_startingwith ","not_startingwith").replaceAll("startingwith ","startingwith"));
                Expression compiledExp = AviatorEvaluator.compile(formulaText.replaceAll("\\s*", ""));
                f.setExpression(compiledExp);
            } catch (Exception e) {
                iter.remove();
                log.error("error====" + e.getMessage() + "====", e);
            } finally {
                continue;
            }
        }
        return formulaList.stream().collect(Collectors.groupingBy(EnipFormula::getNetType));
    }
}
